﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using IcicleFramework.Actions;
using IcicleFramework.Components.Actions;

namespace IcicleFramework.GameServices
{
    public class ActionFactory : GameService, IActionFactory
    {
        protected Dictionary<Type, IAction> cachedActions;

        public ActionFactory()
        {
            cachedActions = new Dictionary<Type, IAction>(128);
        }

        public IAction GenerateAction(XElement element)
        {
            XAttribute classAttrib = element.Attribute("class"),
                         typeAttrib = element.Attribute("type");

            IAction action = null;

            if (classAttrib != null && typeAttrib != null)
            {
                string assembly;

                if (element.Attribute("assembly") != null)
                    assembly = element.Attribute("assembly").Value;
                else
                {
                    string[] temp = classAttrib.Value.Split('.');
                    assembly = temp[0];
                }

                Type classType = Type.GetType(String.Format("{0},{1}", classAttrib.Value, assembly));

                action = RetrieveAction(classType);
                action.Deserialize(element);
            }

            return action;
        }

        public IAction GenerateAction(Type type)
        {
            return RetrieveAction(type);
        }

        protected IAction RetrieveAction(Type type)
        {
            IAction action = null;

            if (!cachedActions.ContainsKey(type))
            {
                action = (IAction) Activator.CreateInstance(type);
                cachedActions.Add(type, action);
            }

            return cachedActions[type].DeepClone();
        }

        public T GenerateAction<T>() where T : IGameAction, new()
        {
            T gameAction = new T();

            return gameAction;
        }
    }
}
